<template>
  <div class="base-container" id="main">
    <t-steps :current="activeForm" status="process" :onChange="onCurChanged">
      <t-step-item title="成果信息" :content="isSubmit('otherId')">
      </t-step-item>
      <t-step-item title="参与人员" :content="isSubmit('memberId')">
      </t-step-item>
      <t-step-item title="成果项目来源" :content="isSubmit('projectId')">
      </t-step-item>
      <t-step-item title="附件信息" :content="isSubmit('fileId')">
      </t-step-item>
    </t-steps>
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
    </t-loading>
    <div class="apply-form">
      <t-form ref="form" :key="activeForm" :colon="true" v-if="activeForm === 0" class="step-form" :data="formData0"
        :rules="rules0" labelWidth="120px">
        <t-row style="flex: 1">
          <t-col :span="12">
            <t-form-item label="成果名称" name="name">
              <t-input clearable style="width: 390px" v-model="formData0.name"></t-input>
            </t-form-item>
            <t-form-item label="颁发单位" name="issueDeptName">
              <t-input clearable style="width: 390px" v-model="formData0.issueDeptName"></t-input>

            </t-form-item>

            <t-form-item label="取得时间" name="obtainDate">
              <t-date-picker clearable style="width: 390px" v-model="formData0.obtainDate"></t-date-picker>
            </t-form-item>
            <t-form-item help="手输支持自定义创建" label="关键词" name="keyWordList">
              <t-select v-model="formData0.keyWordList" creatable filterable multiple placeholder="手输支持自定义创建"
                :options="dict.type.cg_key_word" style="width: 390px;" @create="createKeyWordOptions">
              </t-select>
            </t-form-item>
            <t-form-item label="成果描述" name="performanceInfo">
              <t-textarea v-model="formData0.performanceInfo" :autosize="{ minRows: 5 }" placeholder="请输入您的成果描述" />
            </t-form-item>
            <t-form-item label="备注" name="note">
              <t-textarea v-model="formData0.note" :autosize="{ minRows: 5 }" placeholder="请输入您的备注" />
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="11">

          </t-col>
          <t-col :span="1" class="operation-container">
            <t-button theme="primary" @click="onSubmit0()" type="submit">下一步</t-button>
          </t-col>
        </t-row>
      </t-form>
      <t-form ref="form" :key="activeForm" v-if="activeForm === 1" label-align="top" class="step-form" :data="formData1"
        :rules="rules1" labelWidth="120px">
        <t-row style="flex: 1">
          <t-form-item :show-error-message="false" name="memberList" label="必填">
            <other-member :objId="objId" v-model="formData1.memberList" :editOpen="true"></other-member>
          </t-form-item>
        </t-row>
        <t-row>
          <t-col :span="11">
            <t-space :size="10">
              <t-button @click="onCurChanged(0)" theme="primary" variant="base">上一步
              </t-button>

            </t-space>
          </t-col>
          <t-col :span="1" class="operation-container">
            <t-button theme="primary" @click="onSubmit1()" type="submit">下一步</t-button>
          </t-col>
        </t-row>
      </t-form>
      <t-form ref="form" :key="activeForm" v-if="activeForm === 2" class="step-form" :data="formData2" :rules="rules2"
        labelWidth="120px">
        <t-row style="flex: 1">
          <t-alert style="margin-bottom: 14px;width: 100%" theme="info" title="说明">
            <div slot="message">
              <p class="span-txt">
                内部项目当前系统申报的项目(非必填)
              </p>
              <p class="span-txt">
                外部项目未在当前系统申报的项目(非必填)
              </p>
            </div>
          </t-alert>
          <t-form-item :show-error-message="false" name="projectList">
            <other-project :objId="objId" ref="other-project" :applyData="formData2.applyData"
              v-model="formData2.projectList" :editOpen="true"></other-project>
          </t-form-item>
        </t-row>
        <t-row>
          <t-col :span="11">
            <t-space :size="10">
              <t-button @click="onCurChanged(1)" theme="primary" variant="base">上一步
              </t-button>

            </t-space>
          </t-col>
          <t-col :span="1" class="operation-container">
            <t-button theme="primary" @click="onSubmit2()" type="submit">下一步</t-button>
          </t-col>
        </t-row>
      </t-form>
      <t-form ref="form" :key="activeForm" v-if="activeForm === 3" class="step-form" :data="formData3" :rules="rules3"
        labelWidth="120px">
        <t-row style="flex: 1">
          <t-table row-key="id" :columns="projectFileColumns" :data="projectFileData">
            <template #id="{ row, rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #op="{ row }">
              <file-upload tips="限制pdf、图片" accept="application/pdf,image/*" v-model="row.fileIds"
                :moduleKey="row.moduleKey" :fileList="row.fileLists" :multiple="true">
                <t-button variant="outline">
                  <t-icon name="cloud-upload" slot="icon" />
                  点击上传
                </t-button>
              </file-upload>
            </template>
            <template #c1="{ row }">
              <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
              <div v-else>{{ row.c1 }}</div>
            </template>
          </t-table>
        </t-row>
        <t-row>
          <t-col :span="11">
            <t-space :size="10">
              <t-button @click="onCurChanged(2)" theme="primary" variant="base">上一步
              </t-button>
              <!-- <t-button  theme="primary" @click="onSubmit3(1)" type="submit">暂存</t-button> -->

            </t-space>
          </t-col>
          <t-col :span="1" class="operation-container">
            <t-tooltip content="提交后仍可以修改">
              <t-button :disabled="isCommit" theme="primary" @click="onSubmit3(2)" type="submit">提交</t-button>
            </t-tooltip>
          </t-col>
        </t-row>
      </t-form>
    </div>
  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import otherMember from "./components/other-member.vue";
import otherProject from "./components/other-project.vue";
import { getFiles } from "@/api/common";
import FileUpload from "@/components/FileUpload/index.vue";

export default {
  name: "other-apply",
  dicts: ['cg_key_word'],
  components: {
    otherMember,
    otherProject,
    FileUpload
  },
  data () {
    return {
      site_tag: import.meta.env.VITE_SITE_TAG,
      file_domain: VITE_FILE_DOMAIN,
      projectFileData: [
        {
          id: 1,
          c1: "相关附件",
          c2: "是",
          moduleKey: "otherFJ",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        {
          id: 2,
          c1: "其他",
          c2: "否",
          moduleKey: "otherqt",
          fileIds: [],
          fileLists: [],
          require: false,
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },
        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      objId: null,
      taskId: null,
      applyLoading: false,
      isCommit: false,
      activeForm: 0,
      formData0: {
        keyWordList: [],
        keyWord: '',
        name: '',
        issueDeptName: '',
        performanceInfo: '',
        obtainDate: '',
        note: '',
      },
      rules0: {
        keyWordList: [{ required: true, validator: (val) => val && val.length, message: "关键词不能为空", type: "error" }],
        name: [{ required: true, message: "专利名称不能为空" }],
        // issueDeptName: [{required: true, message: "颁发单位不能为空"}],
        performanceInfo: [{ required: true, message: "成果描述不能为空" }],
        obtainDate: [{ required: true, message: "取得时间不能为空" }],
      },
      formData1: {
        memberList: []
      },
      rules1: {
        memberList: [
          { required: true, validator: (val) => val && val.length, message: "专利发明人不能为空", type: "error" }
        ]
      },
      formData2: {
        projectList: [],
        applyData: []
      },
      rules2: {},
      formData3: {},
      rules3: {},

    }
  },
  watch: {
    activeForm: {
      immediate: true,
      handler (val) {
        const targetEle = document.getElementById("main")
        if (targetEle) {
          const { pos, top } = targetEle.style;
          targetEle.style.position = 'relative';
          targetEle.style.top = '-100px';
          targetEle.scrollIntoView({ behavior: 'smooth', block: 'start', inline: "nearest" });
          targetEle.style.top = top;
          targetEle.style.position = pos;
        }
      }
    }
  },
  created () {
    const taskId = this.$route.params && this.$route.params.taskId;
    if (!taskId) {
      this.$message.error("缺少id");
      return false;
    }
    this.taskId = taskId;
    this.objId = sessionStorage.getItem(`${this.taskId}-other-otherId`);
    const activeForm = Number(sessionStorage.getItem(`${this.taskId}-other-activeForm`)) || 0;
    this.onCurChanged(activeForm, 0);
  },
  methods: {
    onCurChanged (cur, pre) {
      if (Number(cur) !== 0) {
        if (!sessionStorage.getItem(`${this.taskId}-other-otherId`)) {
          this.applyLoading = false;
          this.$message.error("成果信息还未提交")
          return false;
        }
      }
      this.applyLoading = true;
      if (Number(cur) === 0) {
        if (sessionStorage.getItem(`${this.taskId}-other-otherId`)) {
          const otherId = Number(sessionStorage.getItem(`${this.taskId}-other-otherId`));
          this.$api.cgzh.other.get(otherId).then(response => {
            if (response.data) {
              this.formData0.keyWordList = response.data.keyWord?.split(",").filter(item => item !== '')
              Object.assign(this.formData0, response.data)
            }
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-other-activeForm`, cur);
            this.applyLoading = false;
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-other-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 1) {
        this.activeForm = cur;
        sessionStorage.setItem(`${this.taskId}--activeForm`, cur);
        this.applyLoading = false;
      } else if (Number(cur) === 2) {
        // 通过子系统跳转过来录入
        const { serviceCode, serviceId, serviceName, businessId, businessName } = this.$route.query;
        if (businessId) {
          this.formData2.applyData = [
            {
              id: Date.parse(new Date()),
              performanceId: this.objId,
              serviceId: Number(serviceId),
              serviceName,
              serviceCode,
              businessId: Number(businessId),
              businessName,
              isInnerProject: '1',
              projectOptions: [
                {
                  businessId: Number(businessId),
                  businessName,
                }
              ]
            }
          ]
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-other-activeForm`, cur);
          this.applyLoading = false;
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-other-activeForm`, cur);
          this.applyLoading = false;
        }

      } else if (Number(cur) === 3) {
        getFiles(sessionStorage.getItem(`${this.taskId}-other-otherId`)).then((res) => {
          if (res.data.length > 0) {
            sessionStorage.setItem(`${this.taskId}-other-fileId`, res.data.length)
          }
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          this.projectFileData.forEach((val, index) => {
            this.projectFileData[index].fileLists = files[val.moduleKey] || [];
            this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
          })
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-other-activeForm`, cur);
          this.applyLoading = false;
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
      }
      else {
        this.applyLoading = false;
      }
    },
    isSubmit (name) {
      if (sessionStorage.getItem(`${this.taskId}-other-${name}`)) {
        return '已提交'
      }
      return '未提交';
    },
    isSubmitStatus (name) {
      return !!sessionStorage.getItem(`${this.taskId}-other-${name}`);
    },
    onSubmit0 () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.applyLoading = true;
          this.formData0.keyWord = this.formData0.keyWordList.join(",")
          if (!sessionStorage.getItem(`${this.taskId}-other-otherId`)) {
            this.$api.cgzh.other.add({
              ...this.formData0,
            }).then(response => {
              this.objId = response.data.id;
              sessionStorage.setItem(`${this.taskId}-other-otherId`, response.data.id)
              this.$message.success('提交成功');
              this.onCurChanged(1)
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          } else {
            this.$api.cgzh.other.update({
              ...this.formData0,
              id: sessionStorage.getItem(`${this.taskId}-other-otherId`)
            }).then(response => {
              this.$message.success('提交成功');
              this.onCurChanged(1)
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit1 () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.applyLoading = true;
          this.$api.cgzh.other.memberAddList(this.formData1.memberList).then(response => {
            sessionStorage.setItem(`${this.taskId}-other-memberId`, this.formData1.memberList.length)
            this.$message.success('提交成功');
            this.onCurChanged(2)
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit2 () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          const isValidate = this.$refs["other-project"].checkData()
          if (!isValidate) {
            return false;
          }
          this.applyLoading = true;
          this.$api.cgzh.other.projectAddList(this.formData2.projectList).then(response => {
            sessionStorage.setItem(`${this.taskId}-other-projectId`, this.formData2.projectList.length)
            this.$message.success('提交成功');
            this.onCurChanged(3)
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit3 (type) {
      if (type === 1) {
        this.applyLoading = true;
        const sysAttMainIds = []
        this.projectFileData.forEach(val => {
          sysAttMainIds.push(...val.fileIds)
        })
        this.$api.cgzh.other.update({
          id: sessionStorage.getItem(`${this.taskId}-other-otherId`),
          sysAttMainVo: {
            sysAttMainIds,
          }
        }).then(val => {
          sessionStorage.setItem(`${this.taskId}-fileId`, this.projectFileData.length);
          this.$message.success('暂存成功');
          this.applyLoading = false;
          // this.close();
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
      } else {
        const isValidate = this.projectFileData.every(val => {
          if (val.require && val.fileIds.length <= 0) {
            this.$message.error(`需要上传${val.c1}`);
            return false;
          }
          return true
        })
        if (!isValidate) {
          return false
        }
        if (!sessionStorage.getItem(`${this.taskId}-other-otherId`)) {
          this.$message.error("成果信息还未提交")
          this.applyLoading = false;
          return false;
        }
        this.applyLoading = true;
        this.isCommit = true;
        const sysAttMainIds = []
        this.projectFileData.forEach(val => {
          sysAttMainIds.push(...val.fileIds)
        })
        this.$api.cgzh.other.submit({
          id: Number(sessionStorage.getItem(`${this.taskId}-other-otherId`)),
          sysAttMainVo: {
            sysAttMainIds
          }
        }).then(val => {
          sessionStorage.setItem(`${this.taskId}-fileId`, this.projectFileData.length);
          this.$message.success('提交成功');
          this.applyLoading = false;
          this.isCommit = false;
          this.close();
        }).catch((e) => {
          this.applyLoading = false;
          this.isCommit = false;
          this.$message.error(e.toString());
        });
      }
    },
    createKeyWordOptions (value) {
      this.dict.type.cg_key_word.push({
        label: `${value}`,
        value,
      });
    },
    close () {
      this.applyLoading = false;
      setTimeout(() => {
        this.$tab.closeOpenPage({ path: "/cgzh/other/other-my" });
      }, 1000)
    },
  }
}
</script>

<style lang="less" scoped>
.base-container {
  display: flex;
  flex-direction: column;
}

.step-form {
  padding: 0 24px;
  height: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
